<template>
  <div>
    <el-card style="margin-bottom: 20px">
      <CategorySelector @changeCategoryId="changeCategoryId" />
    </el-card>
    <el-card>
      <!-- 平台属性列表 -->
      <div v-show="!isShowAddOrUpdateAttr">
        <!-- 添加书属性按钮 -->
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!category3Id"
          @click="showAddAttr"
          >添加属性</el-button
        >
        <!-- 属性展示 -->
        <el-table
          :data="attrList"
          stripe
          style="width: 100%"
          border
          v-loading="loading"
        >
          <el-table-column label="序号" type="index" width="80" align="center">
          </el-table-column>
          <el-table-column label="属性名称" width="170">
            <template slot-scope="{ row }">
              <el-badge :value="row.attrValueList.length" class="attrName">
                <el-button size="small">{{ row.attrName }}</el-button>
              </el-badge>
            </template>
          </el-table-column>
          <el-table-column label="属性值列表">
            <template slot-scope="{ row }">
              <el-tag
                type="success"
                v-for="(value, index) in row.attrValueList"
                :key="value.id"
                >{{ value.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作" width="150">
            <template slot-scope="{ row }">
              <el-tooltip
                class="item"
                effect="dark"
                content="修改属性"
                placement="top"
              >
                <el-button
                  icon="el-icon-edit"
                  size="small"
                  @click="showUpdateAttr(row)"
                ></el-button>
              </el-tooltip>
              <el-popconfirm
                :title="`确定要删除 ${row.attrName} 吗`"
                @onConfirm="deleteAttr(row.id)"
              >
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除属性"
                  placement="top"
                  slot="reference"
                >
                  <el-button icon="el-icon-delete" size="small"></el-button>
                </el-tooltip>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--添加/修改平台属性及值界面-->
      <div v-show="isShowAddOrUpdateAttr">
        <el-form inline>
          <!--属性名称-->
          <el-form-item label="属性名称">
            <el-input
              type="text"
              v-model="formData.attrName"
              placeholder="输入属性名称"
            ></el-input>
          </el-form-item>
        </el-form>
        <!--两个按钮-->
        <div style="margin-bottom: 20px">
          <el-button type="primary" icon="el-icon-plus" @click="addAttrValue"
            >添加属性值</el-button
          >
          <el-button @click="isShowAddOrUpdateAttr = false">取消</el-button>
        </div>
        <!--表格-->
        <el-table
          :data="formData.attrValueList"
          border
          stripe
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column label="属性值名称">
            <template slot-scope="{ row, $index }">
              <el-input
                :ref="$index"
                v-if="row.edit"
                v-model="row.valueName"
                placeholder="请输入属性值"
                size="mini"
                @keyup.enter.native="toView(row)"
                @blur="toView(row)"
              />
              <span
                v-else
                @click="toEdit(row, $index)"
                style="width: 100%; display: inline-block"
                >{{ row.valueName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{ row, $index }">
              <el-popconfirm
                :title="`确定要删除 ${row.valueName} 吗`"
                @onConfirm="deleteValue($index)"
              >
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="删除属性值"
                  placement="top"
                  slot="reference"
                >
                  <el-button icon="el-icon-delete" size="mini"></el-button>
                </el-tooltip>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!--两个按钮-->
        <div style="margin-top: 20px">
          <el-button type="primary" @click="save" :disabled="!isSaveValid"
            >保存</el-button
          >
          <el-button @click="isShowAddOrUpdateAttr = false">取消</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>
<script>
import CategorySelector from "../components/CategorySelector.vue";
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "Attr",
  components: { CategorySelector },
  data() {
    return {
      category1Id: "", // 一级分类的id
      category2Id: "", // 二级分类的id
      category3Id: "", // 三级分类的id
      attrList: [], //平台属性
      loading: false, // 加载中是否显示
      isShowAddOrUpdateAttr: false, //控制添加界面与显示界面的切换
      formData: {
        attrName: "",
        attrValueList: [],
      },
    };
  },
  computed: {
    isSaveValid() {
      // 判断属性名称和属性值名称是否为空
      return (
        this.formData.attrName.trim() &&
        this.formData.attrValueList.some((attr) => attr.valueName.trim())
      );
    },
  },
  methods: {
    //   获取平台属性
    async getAttrList() {
      const result = await this.$API.attr.getAttrInfoList(
        this.category1Id,
        this.category2Id,
        this.category3Id
      );
      if (result.code == 200) {
        this.attrList = result.data;
        this.loading = false;
      }
    },
    changeCategoryId({ level, categoryId }) {
      if (level === 1) {
        this.category1Id = categoryId;
        // 重置二级/三级分类的id和平台属性数组
        this.category2Id = null;
        this.category3Id = null;
        this.attrList = [];
      } else if (level === 2) {
        this.category2Id = categoryId;
        // 重置三级分类的id和平台属性数组
        this.category3Id = null;
        this.attrList = [];
      } else {
        this.category3Id = categoryId;
        this.loading = true;
        // 调用接口
        this.getAttrList();
      }
    },
    // 点击添加属性
    showAddAttr() {
      this.formData = {
        attrName: "", // 属性名字
        attrValueList: [], // 属性值对象数组
        categoryId: this.category3Id,
        categoryLevel: 3,
      };
      this.isShowAddOrUpdateAttr = true;
    },
    // 根据id删除平台属性
    async deleteAttr(id) {
      const result = await this.$API.attr.deleteAttrInfoById(id);
      if (result.code !== 200) {
        this.$message.error("操作失败");
        return;
      }
      this.$message.success("操作成功");
      this.getAttrList();
    },
    // 修改属性
    showUpdateAttr(attrInfo) {
      this.formData = cloneDeep(attrInfo);
      this.isShowAddOrUpdateAttr = true;
    },
    // 添加属性值
    addAttrValue() {
      this.formData.attrValueList.push({
        // 这个属性是undefined(在添加平台属性的时候,id是没有值,所以,attrId是undefined)
        attrId: this.formData.id, // 存储的是当前平台属性值对象所在的平台属性对象的id
        valueName: "",
        edit: true,
      });
      //   设置当前新的一行有焦点
      this.$nextTick(() => {
        this.$refs[this.formData.attrValueList.length - 1].focus();
      });
    },
    // 添加修改过程中,鼠标失去焦点或点击回车的效果
    toView(value) {
      // 判断是否有数据
      if (value.valueName.trim() === "") return;
      const isRepeat =
        this.formData.attrValueList.filter(
          (val) => val.valueName === value.valueName
        ).length === 2;
      if (isRepeat) {
        // 新录入的数据重复
        this.$message.warning("输入重复数据,请重新输入");
        value.valueName = "";
        return;
      }
      //   转化为查看模式
      value.edit = false;
    },
    // 点击变为修改模式
    toEdit(value, index) {
      // 判断标识是否存在
      if (!value.hasOwnProperty("edit")) {
        this.$set(value, "edit", true);
      } else {
        value.edit = true;
      }
      // 设置对应文本框焦点
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
    },
    // 删除属性值
    deleteValue(index) {
      this.formData.attrValueList.splice(index, 1);
      this.$message.success("删除成功");
    },
    // 保存操作
    async save() {
      // 属性名不存在,不进行保存
      if (this.formData.attrName.trim().length === 0) return;
      // 对属性值对象中的数据过滤操作
      this.formData.attrValueList = this.formData.attrValueList.filter(
        (attrValue) => {
          // 移除编辑或者查看模式的标识
          delete attrValue.edit;
          // 如果属性值为空,直接返回(布尔值效效率更高)
          // return attrValue.valueName.trim()
          return !!attrValue.valueName.trim();
        }
      );
      //   如果属性值为空,不进行保存
      if (this.formData.attrValueList.length === 0) {
        this.$message.warning("至少添加一个属性值");
        return;
      }
      const result = await this.$API.attr.addOrUpdateAttrInfo(this.formData)
      if (result.code !== 200) {
        this.$message.error('操作失败')
        return
      }
      this.$message.success('操作成功')
    // 关闭当前页面  
      this.isShowAddOrUpdateAttr = false
      this.getAttrList() // 刷新
    },
    // 删除平台属性
    async deleteAttr(attrId) {
      const result = await this.$API.attr.deleteAttrInfoById(attrId)
      if (result.code !== 200) {
        this.$message.error('操作失败')
        return
      }
      this.$message.success('操作成功')
      this.getAttrList()
    },
  },
};
</script>
<style>
.attrName {
  margin-top: 20px;
  margin-right: 20px;
}
.item {
  margin: 4px;
}
</style>